package com.jdy.haoduoai.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.model.ImageItem;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.Tools;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXVideoObject;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

//import com.jdy.haoduoai.R;

public class SharePopupWindow extends BaseActivity implements OnClickListener
/* Response */{

  private static final int WX_THUMB_SIZE = 120;

  @InjectView(id = R.id.pop_layout)
  private LinearLayout layout;
  @InjectView(id = R.id.sharepyq, click = true)
  private ImageView pyq;
  @InjectView(id = R.id.shareqq, click = true)
  private ImageView qq;
  @InjectView(id = R.id.sharesina, click = true)
  private ImageView sina;
  @InjectView(id = R.id.sharewx, click = true)
  private ImageView wx;
  public static Tencent mTencent;
  @SuppressWarnings("unused")
  private String name, pic, babyname, nickname, share_data, title, Summary,
      url, av;
  private int id;
  private IWXAPI api;
  private boolean sharepic;
  private boolean localpic; // 本地照片
  private String Sharedlink; // 照片墙
  ArrayList<ImageItem> picList;

  @SuppressWarnings("unchecked")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.share_selector);
    hideTitleView();
    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT);
    mTencent = Tencent.createInstance(Constant.QQ_APP_ID,
        this.getApplicationContext());

    api = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID);
    api.registerApp(Constant.WX_APP_ID);

    Intent intent = getIntent();
    name = intent.getStringExtra("name");
    pic = intent.getStringExtra("pic");
    id = intent.getIntExtra("id", 0);
    Sharedlink = intent.getStringExtra("Sharedlink");
    sharepic = intent.getBooleanExtra("sharepic", false);
    localpic = intent.getBooleanExtra("localpic", false);
    av = intent.getStringExtra("av");

    picList = (ArrayList<ImageItem>) intent.getSerializableExtra("picList");
    share_data = intent.getStringExtra("share_data");

    babyname = LeConfig.babyname;
    nickname = LeConfig.nickname;

    title = nickname + "给" + babyname + "讲了一个故事";
    Summary = babyname + "的" + nickname + "使用好多爱家长版给" + babyname + "讲了一个《" + name
        + "》的故事";

    if (Tools.isNotEmpty(av)) {
      url = av;
    } else {
      url = "http://sapi.jdy520.com/h5/share/index.html?id=" + id;
    }

    // 添加选择窗口范围监听可以优先获取触点，即不再执行onTouchEvent()函数，点击其他地方时执行onTouchEvent()函数销毁Activity
    layout.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        toastShow("提示：点击窗口外部关闭窗口！");
      }
    });
  }

  // 实现onTouchEvent触屏函数但点击屏幕时销毁本Activity
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    finish();
    return true;
  }

  @Override
  public void onClick(View v) {

    switch (v.getId()) {
    case R.id.sharewx:
      share2weixin(0);
      break;
    case R.id.sharepyq:
      share2weixin(1);
      break;
    case R.id.shareqq:
      onQQClickShare();
      break;
    }
  }

  public boolean isAvilible(Context context, String packageName) {
    PackageManager packageManager = context.getPackageManager();

    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
    for (int i = 0; i < pinfo.size(); i++) {
      if (pinfo.get(i).packageName.equalsIgnoreCase(packageName))
        return true;
    }
    return false;
  }

  private ArrayList<Uri> getUriListForImages() {
    ArrayList<Uri> myList = new ArrayList<Uri>();
    if (picList.size() != 0) {
      for (int i = 0; i < picList.size(); i++) {
        if (picList.get(i).isSelected) {
          try {
            myList.add(Uri.fromFile(new File(picList.get(i).sourcePath)));
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }

    return myList;
  }

  private void onQQClickShare() {
    if (localpic) {
      if (!isAvilible(this, "com.tencent.mobileqq")) {
        Toast.makeText(this, "未安装" + "分享给QQ好友", Toast.LENGTH_SHORT).show();
        return;
      }

      Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);

      intent.setType("image/*");
      intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,
          getUriListForImages()/*
                                * Uri.fromFile (f)
                                */);

      intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
      intent.putExtra(Intent.EXTRA_TITLE, "宝宝照片");
      intent.putExtra(Intent.EXTRA_TEXT, "宝宝照片");
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

      startActivity(Intent.createChooser(intent, "请选择"));

    } else {
      final Bundle params = new Bundle();
      params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
          QQShare.SHARE_TO_QQ_TYPE_DEFAULT);

      if (sharepic || Tools.isNotEmpty(Sharedlink)) {
        title = "好多爱家长版|来自" + nickname + "的记录";
        Summary = "好多爱家长版照片墙";
      }

      if (Tools.isNotEmpty(av)) {
        title = name;
        Summary = share_data;
        url = av;
      }

      params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
      params.putString(QQShare.SHARE_TO_QQ_SUMMARY, Summary);

      if (Tools.isNotEmpty(Sharedlink)) {
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, Sharedlink);
      } else {
        if (sharepic) {
          params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, pic);
        } else {
          params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
        }
      }

      // if (Tools.isNotEmpty(av)) {
      // params.putString(QQShare.SHARE_TO_QQ_AUDIO_URL, url);
      // }

      params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, pic);
      mTencent.shareToQQ(SharePopupWindow.this, params, new BaseUiListener());
    }
  }

  private class BaseUiListener implements IUiListener {

    @Override
    public void onComplete(Object response) {
      if (null == response) {
        System.out.println("========返回为空===登录失败====");
        return;
      }
      JSONObject jsonResponse = (JSONObject) response;
      if (null != jsonResponse && jsonResponse.length() == 0) {
        System.out.println("========返回为空===登录失败====");
        return;
      }
      System.out.println("===========登录成功====");
      doComplete((JSONObject) response);
    }

    protected void doComplete(JSONObject values) {

    }

    @Override
    public void onError(UiError e) {

    }

    @Override
    public void onCancel() {

    }
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // mWeiboShareAPI.handleWeiboResponse(intent, this); // 当前应用唤起微博分享后，返回当前应用
  }

  private String buildTransaction(final String type) {
    return (type == null) ? String.valueOf(System.currentTimeMillis()) : type
        + System.currentTimeMillis();
  }

  private Bitmap compressBitmapNew(String file, int target) {
    BitmapFactory.Options oriOptions = new BitmapFactory.Options();
    oriOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(file, oriOptions);
    if (oriOptions.outWidth > 0 && oriOptions.outHeight > 0) {
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = false;
      options.inSampleSize = getSampleSize(
          Math.max(oriOptions.outHeight, oriOptions.outHeight), target);
      return BitmapFactory.decodeFile(file, options);
    }
    return null;
  }

  private int getSampleSize(int size, int targetSize) {
    if (size <= 0 || targetSize <= 0) {
      return 1;
    }
    int result = 1;
    while (size > targetSize) {
      size /= 2;
      result *= 2;
    }
    return result;
  }

  private void share2weixin(final int flag) { // flag 0是朋友圈，1是好友
    if (!api.isWXAppInstalled()) {
      toastShow("您还未安装微信客户端");
      return;
    }

    WXWebpageObject webpage = new WXWebpageObject();
    webpage.webpageUrl = url;
    final WXMediaMessage msg = new WXMediaMessage(webpage);
    msg.title = title;
    msg.description = Summary;

    if (localpic) {
      if (sharepic) {
        WXImageObject imageObject = new WXImageObject();
        // imageObject.imageData = bmpToByteArray(shareBitBmp, true);
        imageObject.setImagePath(pic);
        WXMediaMessage msg0 = new WXMediaMessage(imageObject);
        msg0.mediaObject = imageObject;

        Bitmap bmp = BitmapFactory.decodeFile(pic);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 120, 120, true);
        bmp.recycle();
        msg0.thumbData = bmpToByteArray(thumbBmp, true);

        // msg0.thumbData = bmpToByteArray(thumbBmp, true);

        String mShareTitle = null;
        mShareTitle = "好多爱家长版|来自" + nickname + "的记录";
        msg0.title = mShareTitle;
        msg0.description = "好多爱家长版照片墙";
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg0;
        req.scene = flag;
        api.sendReq(req);
      }
    } else {
      if (Tools.isNotEmpty(Sharedlink)) { // 分享照片墙
        webpage.webpageUrl = Sharedlink;
        String mShareTitle = null;
        mShareTitle = "好多爱家长版|来自" + nickname + "的记录";
        msg.title = mShareTitle;

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        msg.description = "好多爱家长版照片墙";
        req.scene = flag;
        api.sendReq(req);
      } else if (Tools.isNotEmpty(pic)) {
        new AsyncTask<String, Void, Bitmap>() {
          @SuppressWarnings("deprecation")
          @Override
          protected Bitmap doInBackground(String... params) {
            Bitmap resultImage = null;
            try {
              String requestUrl = URLEncoder.encode(params[0])
                  .replace("%3A", ":").replace("%2F", "/");

              URL url = new URL(requestUrl);
              HttpURLConnection urlConnection = (HttpURLConnection) url
                  .openConnection();
              urlConnection.setRequestMethod("GET");
              urlConnection.connect();
              InputStream in = urlConnection.getInputStream();
              resultImage = BitmapFactory.decodeStream(in);
              return resultImage;
            } catch (IOException e) {
              return null;
            }
          }

          @Override
          protected void onPostExecute(Bitmap result) {
            if (result != null) {
              Bitmap thumbBmp = Bitmap.createScaledBitmap(result,
                  WX_THUMB_SIZE, WX_THUMB_SIZE, true);
              result.recycle();

              if (sharepic) {
                WXImageObject imageObject = new WXImageObject();
                imageObject.imageData = bmpToByteArray(thumbBmp, true);

                WXMediaMessage msg = new WXMediaMessage(imageObject);
                msg.thumbData = imageObject.imageData;

                String mShareTitle = null;
                mShareTitle = "好多爱家长版|来自" + nickname + "的记录";
                msg.title = mShareTitle;
                msg.description = "好多爱家长版照片墙";
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("img");
                req.message = msg;
                req.scene = flag;
                api.sendReq(req);
              } else {
                if (Tools.isNotEmpty(av)) {
                  WXWebpageObject webpage = new WXWebpageObject();
                  webpage.webpageUrl = url;
                  msg.title = name;
                  msg.description = share_data;

                  WXMediaMessage msg = new WXMediaMessage(webpage);
                  msg.title = name;
                  msg.description = share_data;
                  msg.thumbData = bmpToByteArray(thumbBmp, true);

                  SendMessageToWX.Req req = new SendMessageToWX.Req();
                  req.transaction = buildTransaction("webpage");
                  req.message = msg;
                  req.scene = flag;
                  api.sendReq(req);
                } else {
                  WXVideoObject video = new WXVideoObject();
                  video.videoUrl = url;
                  WXMediaMessage msg = new WXMediaMessage(video);
                  msg.title = title;
                  msg.description = Summary;

                  msg.thumbData = bmpToByteArray(thumbBmp, true);

                  SendMessageToWX.Req req = new SendMessageToWX.Req();
                  req.transaction = buildTransaction("video");
                  req.message = msg;
                  req.scene = flag;
                  api.sendReq(req);
                }

              }
            }
          }

        }.execute(pic);
      }
    }
  }

  public static byte[] bmpToByteArray(Bitmap paramBitmap, boolean paramBoolean) {
    byte[] retByte;
    ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
    paramBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
        localByteArrayOutputStream);
    if (paramBoolean) {
      paramBitmap.recycle();
    }
    retByte = localByteArrayOutputStream.toByteArray();
    try {
      localByteArrayOutputStream.close();
    } catch (Exception localException) {
      // localException;
    }
    return retByte;
  }
}
